//
//  BindCardListController.m
//  EasyCar
//
//  Created by nsm on 2018/1/9.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "BindCardListController.h"
#import "CardAddController.h"

@interface BindCardListCell : NSMTableViewCell {
    UIImageView *_iconImageView;
    UILabel     *_titleLabel;
    UIButton    *_statusBtn;
}
@end

@implementation BindCardListCell
- (void)setObject:(id)obj {
    BOOL isDefault = [obj[@"is_default"] isEqual:@"1"];
    if (isDefault) {
        _statusBtn.enabled = NO;
        [_statusBtn setTitle:@"已默认" forState:UIControlStateNormal];
        ViewBorder(_statusBtn, 0, [UIColor clearColor]);
        ViewCorner(_statusBtn, 0);
    } else {
        _statusBtn.enabled = YES;
        [_statusBtn setTitle:@"默认" forState:UIControlStateNormal];
        ViewBorder(_statusBtn, 1, [UIColor lightGrayColor]);
        ViewCorner(_statusBtn, 5);
    }
    
    NSUInteger len = [obj[@"card"] length];
    NSString *card = [obj[@"card"] substringWithRange:NSMakeRange(MAX(0, len-4), MIN(len, 4))];
    card = FormatString(@"\n**** %@ (%@)",card, obj[@"name"]);
    _titleLabel.attributedText = AttributedString(obj[@"bank_name"],
                                                  BoldSystemFont(16),
                                                  [UIColor darkGrayColor],
                                                  card,
                                                  CustomFont(14),
                                                  [UIColor darkGrayColor],
                                                  NSTextAlignmentLeft,
                                                  0);
    [_iconImageView setImageURL:obj[@"logo"]];
}

- (void)setupSubviews {
    UIView *bgView = [UIView new];
    bgView.size = CGSizeMake(kScreenWidth, 64);
    bgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bgView];
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    layout.mySize = CGSizeMake(bgView.width, 64);
    layout.padding = UIEdgeInsetsMake(0, 15, 0, 15);
    layout.subviewHSpace = 12;
    layout.gravity = MyGravity_Vert_Center;
    [bgView addSubview:layout];
    
    _iconImageView = [UIImageView new];
    _iconImageView.mySize = CGSizeMake(40, 40);
    [layout addSubview:_iconImageView];
    
    _titleLabel = [UILabel new];
    _titleLabel.weight = 1;
    _titleLabel.wrapContentHeight = YES;
    [layout addSubview:_titleLabel];

    _statusBtn = [UIButton new];
    _statusBtn.mySize = CGSizeMake(48, 24);
    _statusBtn.titleLabel.font = CustomFont(13);
    [_statusBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [layout addSubview:_statusBtn];
    
    [_statusBtn addTarget:self action:@selector(changeDefault:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)changeDefault:(UIButton *)btn {
    !self.actionBlock?:self.actionBlock(nil);
}

@end

@interface BindCardListController ()
@end

@implementation BindCardListController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initNavigationItems];
    [self createTableView];
}

- (void)initNavigationItems {
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItemAction)];
    self.navigationItem.rightBarButtonItem = addItem;
}

- (void)createTableView {
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavBarHeight);
    self.tableView.rowHeight = 64;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    UIView *header = [UIView new];
    header.size = CGSizeMake(kScreenWidth, 15);
    self.tableView.tableHeaderView = header;
    self.tableView.tableFooterView = [UIView new];
    
    self.tableView.headerRefreshEnabled = YES;
    self.tableView.footerRefreshEnabled = YES;
    self.tableView.emptySetEnabled = YES;
    self.tableView.urlString = @"mine/cardList.html";
    
    @nsm_weak(self)
    self.tableView.sourceManager.classForCellAtIndexPath = ^Class(NSIndexPath *indexPath) {
        return [BindCardListCell class];
    };
    self.tableView.sourceManager.actionForCellAtIndexPath = ^CellActionBlock(NSIndexPath *indexPath) {
        @nsm_strong(self)
        return ^(id obj) {
            NSDictionary *item = self.tableView.sourceManager.dataArray[indexPath.row];
            [self changeToDefaultCar:item[@"id"]];
        };
    };
    self.tableView.didRefreshingHeaderSuccess = ^(id responseObject) {
        @nsm_strong(self)
        id data = ((NSMResponseObject *)responseObject).data;
        self.tableView.sourceManager.dataArray = [NSMutableArray arrayWithArray:data[@"list"]];
    };

    self.tableView.didRefreshingFooterSuccess = ^(id responseObject) {
        @nsm_strong(self)
        id data = ((NSMResponseObject *)responseObject).data;
        [self.tableView.sourceManager.dataArray addObjectsFromArray:data[@"list"]];
    };
    self.tableView.didRefreshingHeaderEmpty = ^(id responseObject) {
        @nsm_strong(self)
        self.tableView.imageForEmptySet = kEmptyDataImage;
        self.tableView.titleForEmptySet = kEmptyDataDesc(((NSMResponseObject *)responseObject).desc);
    };
    
    [self.tableView beginRefreshing:RefreshHudDefault];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.layer.zPosition = indexPath.row;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *item = tableView.sourceManager.dataArray[indexPath.row];
    !self.didSelectedCard?:self.didSelectedCard(item);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - nav
- (void)addItemAction {
    CardAddController *vc = [CardAddController new];
    vc.title = @"添加银行卡";
    @nsm_weak(self)
    vc.didAddCardSuccess = ^{
        @nsm_strong(self)
        [self.tableView beginRefreshing:RefreshHudDefault];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)changeToDefaultCar:(NSString *)carID {
    /**
     * 用户设置默认提现账号接口
     * 接口实例：http://zuche.test.beisheng.wang/index.php/Api/User/setDefault.html
     * uin           [用户id]*必传
     * id            [账号标识ID]*必传
     */
    [_networker POST:@"mine/setDefault.html" parameters:@{@"id": SafeString(carID)} success:^(NSMResponseObject *responseObject) {
        [self.tableView beginRefreshing:RefreshHudDefault];
    } empty:nil failure:nil];
}

@end
